package za.co.felixsol.sf.gcode.instructions.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import za.co.felixsol.sf.gcode.Program;
import za.co.felixsol.sf.gcode.instructions.AxisInstruction;
import za.co.felixsol.sf.gcode.instructions.Instruction;
import za.co.felixsol.sf.gcode.instructions.InstructionParameter;

public class BasicInstructionWriter implements InstructionWriter {

	private OutputStream outputStream;

	public BasicInstructionWriter(OutputStream outputStream) {
		this.outputStream = outputStream;
	}

	@Override
	public void write(Program program) throws IOException {
		for (Instruction instruction : program.getInstructions()) {
			write(instruction);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void write(Instruction instruction) throws IOException {

		if (instruction != null) {
			String instructionS = instruction.getGCode();
			List<InstructionParameter> parameters = new ArrayList<InstructionParameter>(instruction.getParameters());
			Collections.sort(parameters, new InstructionParameter.InstructionParameterComparator());
			if (parameters.size() > 0) {
				for (InstructionParameter parameter : parameters) {
					instructionS += " ";
					instructionS += parameter.getName();
					instructionS += parameter.getValue();
				}
			}
			instructionS += "\n";
			outputStream.write(instructionS.getBytes());
		}

	}

}
